<template>
  <div class="classroom-borrowing-application">
    <!-- 筛选条件 -->
    <condition-card :label-width="'130px'" @reset="reset" @search="initData">
      <el-row>     
        <el-col :span="8">
          <el-form-item label="学期">
            <CalendarSelect v-model="query.calendarId" @load-done="calendarLoadDone" :all="true"></CalendarSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用途">
            <DictSelect :plzSelect="true" v-model="query.borrowingUse" :data="options.useing" :clearable="true" :exclude="usageExclude" ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="校区">
            <DictSelect :plzSelect="true" v-model="query.campus" :data="options.campus" @change="handelCampusChang" :clearable="true" ></DictSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="教学楼">
            <DictSelect :plzSelect="true" v-model="query.towerCode" :clearable="true" :filterable="true" :data="teachingBuildingArr" ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="教室名称">
            <el-input v-model="query.classroomName" placeholder="请输入" :clearable="true" maxlength="15"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借用人">
            <el-input v-model="query.borPerson" placeholder="请输入" :clearable="true" maxlength="15"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="借用说明">
            <el-input v-model="query.borExplain" placeholder="请输入" :clearable="true" maxlength="15" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核状态">
            <DictSelect :plzSelect="true" v-model="query.applyStatus" :data="options.applyStatus" ></DictSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="query.show">
        <el-col :span="8">
            <el-form-item label="管理部门">
                <el-select v-model="query.projectId" style="width: 100%" :clearable="true">
                    <el-option v-for="item in projectIdList" :key="item.value" :label="item.label" :value="item.value" ></el-option>
                </el-select>
            </el-form-item>
        </el-col>
      </el-row>
    </condition-card>

    <!-- 基本信息列表 -->
    <el-card shadow="never">
      <div class="edu-opertion-bar">
        <!-- <h2>教室借用申请</h2> -->
        <div class="float-left">
          <el-input v-model="query.conditionValue" :placeholder="'请输入教室名称/教学楼名称'" suffix-icon="el-icon-search" :clearable="true"
          @change="handSearchChang" style="width:240px" @keyup.enter.native="initData" maxlength="15" />
        </div>
        <div class="float-right">
          <el-button @click="applicate" type="primary" icon="el-icon-news" >申请</el-button>
          <el-button  @click="exportApply" type="success" icon="el-icon-printer" plain >导出教室借用单</el-button>
          <el-button  @click="exportExcel" icon="el-icon-download" >导出Excel</el-button>
        </div>
        <div class="clear-both"></div>
      </div>
      <EduTable :order="true" :selection="true" :border="false" :data="borrowingRoomList.data" :total="borrowingRoomList.total" :pageSize="query.pageSize_"
        :pageNum="query.pageNum_"  class="classroomTable" @page-change="pageChange" @selection-change="handleSelectionChange" >
        <el-table-column label="借用说明"  min-width="70">
          <template slot-scope="scope">
            <el-tooltip placement="top" :content="scope.row.borExplain" effect="light">
              <span>{{scope.row.borExplain}}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="用途"  min-width="50">
          <template slot-scope="scope">{{scope.row.borrowingUseI18n}}</template>
        </el-table-column>
        <el-table-column label="教室名称" min-width="90" show-overflow-tooltip>
          <template slot-scope="scope">
              <!-- <span :title="scope.row.classroomNameStr.split('|').join('\n')"  v-html="scope.row.classroomNameShortStr"></span> -->
              <span>{{scope.row.classroomNameShortStr}}</span>
          </template>
        </el-table-column>
        <el-table-column label="校区"  min-width="70">
          <template slot-scope="scope">{{scope.row.campusStr}}</template>
        </el-table-column>
        <el-table-column label="教学楼" min-width="70" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.towerNameStr}}</span>
          </template>
        </el-table-column>
        <el-table-column label="借用学期" min-width="80">
          <template slot-scope="scope">{{scope.row.calendarNameStr}}</template>
        </el-table-column>
        <el-table-column label="借用时间"  min-width="230" >
          <template slot-scope="scope">
            <!-- <span :title="scope.row.mergeBorTimeStr.split('|').join('\n')" v-html="scope.row.mergeBorTimeShortStr"></span> -->
            <span :title="scope.row.mergeBorTimeStr.split('|').join('\n')" >{{scope.row.mergeBorTimeShortStr}}</span>
          </template>
        </el-table-column>
        <el-table-column label="借用人" min-width="70" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.borPerson}}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" min-width="80">
          <template slot-scope="scope">{{scope.row.applyTime}}</template>
        </el-table-column>
        <el-table-column label="审核状态" min-width="60">
          <template slot-scope="scope">
            <el-tag size="mini" type="info" v-if="scope.row.applyStatus == '1' || scope.row.applyStatus === null">{{scope.row.applyStatusI18n}}</el-tag>
            <el-tag size="mini" type="danger" v-if="scope.row.applyStatus == '2'">{{scope.row.applyStatusI18n}}</el-tag>
            <el-tag size="mini" type="success" v-if="scope.row.applyStatus == '3'">{{scope.row.applyStatusI18n}}</el-tag>
            <el-tag size="mini" type="warning" v-if="scope.row.applyStatus == '4'">{{scope.row.applyStatusI18n}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('message.operating')" min-width="80">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="showDetails(scope.row)">查看</el-button>
            <el-button type="text" size="mini" v-show="(scope.row.applyStatus == '2' || scope.row.applyStatus == '4') && (scope.row.chargePersonId == global.currentUser.uid || scope.row.borPersonCode == global.currentUser.uid) " @click="edit(scope.row)">修改</el-button>
            <el-button type="text" size="mini" v-show="scope.row.applyStatus == '1' && (scope.row.chargePersonId == global.currentUser.uid || scope.row.borPersonCode == global.currentUser.uid)" @click="cancel(scope.row)">撤回</el-button>
          </template>
        </el-table-column>
      </EduTable>
    </el-card>
  </div>
</template>

<script>
import Calendars from "common/src/api/calendars";
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import * as API from "common/src/api/resource/classroom";
import mixin from 'common/src/mixins/index';
export default {
  name: "classroomBorrowingApplication", mixins: [mixin],
  data() {
    return {
      query: {
        pageNum_: 1,
        pageSize_: 20,
        calendarId: "",
        borrowingUse: "",
        campus: "",
        towerCode: "",
        classroomName: "",
        borPerson: "",
        borExplain: "",
        applyStatus: "",
        conditionValue: "", projectId:"", show:false,
        id:"",
        ids:[]
      },
      teachingBuildingArr: [], projectIds: [],
      defaultQuery: {
        pageNum_: 1,
        pageSize_: 20,
        calendarId: "",
        borrowingUse: "",
        campus: "",
        towerCode: "",
        classroomName: "",
        borPerson: "",
        borExplain: "",
        applyStatus: "",
        conditionValue: "",
        id:"",
        ids:[], projectId:"",
      },
      // 下拉框数据
      options: { campus: [], useing: [], applyStatus: [] },
      borrowingRoomList: { data: [], total: 0 },
      //当前学期
      currentTermCalendar:"",
      selectData:[],
      //排除教室用途为01,02 为排考模块儿，排课模块儿专用
      usageExclude:["01","02"], 
      projectIdList: [{ label: "本科生", value: "1" }, { label: "普通研究生", value: "2" }, { label: "研究生在职教育", value: "4" }],
      mainCalendarId:""
    };
  },

  methods: {
    calendarLoadDone(list){
			if(list) {
        this.allCalendarList = list;
			 for (let index = 0; index < list.length; index++) {
				 const element = list[index];
				 if (element.currentTermFlag) {
          this.currentTermCalendar = element.id;
          this.totalWeekNumber = element.weekNum;
					break;
				}
			 }
			}
    },

    // 获取下拉框数据（数据字典）
    initOptions() {
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_XQ","X_JSYT","X_JSSHZT"]
      };
      queryDic(data).then(res => {
        if (res.code == 200) {
          UTILS.fillSelect(
            {
              campus: "X_XQ",
              useing: "X_JSYT",
              applyStatus: "X_JSSHZT"
            },
            res.data,
            this.options
          );
        }
      });
    },
    //把教室名称数据转换成需要展示的样子
    getClassroomNameStrByList(list) {
      let str = "";
      let tempList = [];
      if (list != null) {
        list.forEach(index => {
          let classroomName = index.classroomName;
          if (!tempList.includes(classroomName)) {
             str += classroomName + " |";
              tempList.push(classroomName);
          }
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把借用时间转换成需要展示的样子
    getBorTimeStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.borTimeStr + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把校区数据转换成需要展示的样子
    getCampusStrByList(list) {
      let str = "";
      if (list != null) {
        str = list[0].campusI18n;
      }
      return str;
    },
    //把学期数据转换成需要展示的样子
    getCalendarNameStrByList(list) {
      let str = "";
      if (list != null) {
        str = list[0].calendarName;
      }
      return str;
    },
    getCalendarIdByList(list) {
      let str = "";
      if (list != null) {
        str = list[0].calendarId;
      }
      return str;
    },
    //把校区数据转换成需要展示的样子
    getTowerNameStrByList(list) {
      let str = "";
      let towerNameList = [];
      if (list != null) {
        list.forEach(index => {
          let towerName = index.towerName;
          if (towerName && !towerNameList.includes(towerName)) {
            towerNameList.push(index.towerName);
            str += index.towerName + " |";
          }
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },

    reset() {
      this.query = JSON.parse(JSON.stringify(this.defaultQuery));
      //学期为当前学期
      this.query.calendarId = this.currentTermCalendar;
      this.getClassroomApplyInfoList();
      this.handelCampusChang(null);
      this.getListInfoCount(); // 初始化判断管理部门是否显示add by quanwei
    },
    initData() {
      this.query.pageNum_ = 1;
      this.getClassroomApplyInfoList();
    },

    async getClassroomApplyInfoList(){
      let res = await API.getClassroomApplyInfoList(this.query);
      if (res && res.code == 200) {
        _.forEach(res.data.list, item => {
          item.classroomNameStr = this.getClassroomNameStrByList(item.classroomApplyDetailVoList);
          item.classroomNameShortStr = this.convertClassroomNameListStr(item.classroomApplyDetailVoList); // 教室名称
          item.mergeBorTimeShortStr = this.convertmergeBorTimeStr(item.mergeBorTimeStr.split('|'));
          item.campusStr = this.getCampusStrByList(item.classroomApplyDetailVoList);
          item.towerNameStr = this.getTowerNameStrByList(item.classroomApplyDetailVoList);
          let towerCode = item.classroomApplyDetailVoList[0].towerCode;
          item.towerCode = towerCode && towerCode.split(",");
          item.calendarNameStr = this.getCalendarNameStrByList(item.classroomApplyDetailVoList);
          item.calendarId = this.getCalendarIdByList(item.classroomApplyDetailVoList);
        });
        this.borrowingRoomList.data = res.data.list;
        this.borrowingRoomList.total = res.data.total_;
        this.query.pageSize_ = res.data.pageSize_;
        this.query.pageNum_ = res.data.pageNum_;

        let projectId = this.query.projectId;
        if(this.query.show){ // 管理部门显示
           if(projectId == ""){
             this.query.projectId = "1"; // 1本科，2研究生，4在职
           }
        }else{
            // 老师为单个部门时需要传当前projectId值
            // this.query.projectId = this.$store.getters.getProjectId();

            // 如果部门不显示，则不传projectId
            // this.query.projectId = "";

             if(this.global.isAdmin || this.global.isAcdemicDean){
                this.query.projectId = this.$store.getters.getProjectId();
             }else{
               this.query.projectId = "";
             }
        }
        
      }
    },
    convertClassroomNameListStr(list) {
      if (!list)
        return "";
      if (list.length){
        let tempList = list.map(t => `${t.classroomName}`);
        let uniqueList = [...new Set(tempList)];
        return uniqueList && uniqueList.length ? uniqueList.reduce((a, b) => a +(",") + b) : "";
      }
    },
    convertmergeBorTimeStr(list){
      if (!list)
        return "";
      if (list.length){
      return list && list.length ? list.map(t => `${t}`).reduce((a, b) => a +(",") + b) : "";
      }
    },
    pageChange(val) {
      this.query.pageNum_ = val.pageNum;
      this.query.pageSize_ = val.pageSize;
      this.getClassroomApplyInfoList();
    },
    handleSelectionChange(val) {
      this.query.ids = val.map(item => {
        return item.id;
      });
      this.selectData = val;
    },
    // 查询教学楼字典数据
    handelCampusChang(item) {
      this.teachingBuildingArr = [];
      this.query.towerCode = "";
      let params = {
        campus: item
      };
      API.conditionQueryByDict(params).then(res => {
        _.forEach(res.data.list, item => {
          this.teachingBuildingArr.push({
            value: item.code,
            label: item.name
          });
        });
      });
    },
    //撤销教室借用
    cancel(data){
      this.$delConfirm("确定要撤销 [ "+data.borExplain+" ] 吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        API.cancelClassroomApply(data.id).then(res =>{
          if (res.code == 200) {
              this.$message({ type: "success", message: "撤销成功!" });
              this.getClassroomApplyInfoList();
            } else {
              this.$message({ type: "info", message: res.msg });
            }
        });
      }).catch(e => {});
    },
    //修改教室借用单
    edit(data){
      this.$router.push({
        path: "/roomBorrowingInfo",
        query: {
          //2为更新教室借用申请单 
          pageType: "2",
          applyData: data
        }
      });
    },
    showDetails(data) {
      this.$router.push({
        path: "/roomBorrowingInfo",
        query: {
          //3为详情
          pageType: "3",
          applyData: data
        }
      });
    },
    // 导出借用申请单
    exportApply() {
      if (this.selectData.length != 1 ){
        this.$message({
              type: "warning",
              message: " 请只选择选择一条记录"
            });
      } else {
        this.selectData.forEach(index => {
          //如果不是审核通过的
          if (index.applyStatus != '3') {
            this.$message({
              type: "warning",
              message: "审核不通过的不能导出申请单！"
            });
          } else {
            let res = API.exportApply({"id" : index.id});
          }
        })
      }
    },
    /**
     * 导出Excel
     */
    exportExcel() {
      let params = {
        calendarId: this.query.calendarId,
        borrowingUse: this.query.borrowingUse,
        campus: this.query.campus,
        towerCode: this.query.towerCode,
        classroomName: this.query.classroomName,
        borPerson: this.query.borPerson,
        borExplain: this.query.borExplain,
        applyStatus: this.query.applyStatus,
        teacherCode: this.query.teacherCode,
        ids: this.selectData.map(item => {
          return item.id
        })
      }
      API.exportExcel(params);
    },

    handSearchChang(string) {
            this.initData();
        },

    // 申请
    applicate() {
       let flag = false;
       let newprojectId = this.query.projectId; // 管理部门
        if(!this.query.show){ // 管理部门不显示
          newprojectId = "";
          flag = true;
        }else{
          if(newprojectId == "" || newprojectId == undefined){
            this.$message({type: "warning", message: "提示：请先选择管理部门!"});
            return
          }

          // 判断当前用户根据“管理部门”是否有权限进行申请操作
          this.projectIds.forEach(el => {
            console.log("1.2->el = " + el + ",newprojectId = " + newprojectId);
             if(el == newprojectId){
                flag = true;
             }
          })
        }

        if(flag){
          console.log("1.1->newprojectId = " + newprojectId);
            this.$router.push({
              path: "/roomBorrowingInfo",
              query:{newprojectId: newprojectId}
            });
        }else{
            if(newprojectId == "1"){
              this.$message({type: "warning", message: "提示：您在管理部门-本科生无权限进行操作!"});
            }else if(newprojectId == "2"){
              this.$message({type: "warning", message: "提示：您在管理部门-普通研究生无权限进行操作!"});
            }else if(newprojectId == "4"){
              this.$message({type: "warning", message: "提示：您在管理部门-研究生在职教育无权限进行操作!"});
            }
        }
    },

    // 初始化判断管理部门是否显示add by quanwei
    getListInfoCount(){
      this.projectIds = [];
      this.query.teacherCode = this.global.currentUser.uid;
      API.getListInfoCount(this.query).then(response => {
        if (response.code === 200) {
          response.data.forEach(el => {
            this.projectIds.push(el.projectId);
          })
           let count = response.data.length;
            if(count > 1 && this.query.show != true){
              // this.query.show
              this.query.show = true;
            }
        }
      })
    },

    // 获取当前学年学期
    getTimeData(){
        Calendars.currentTermCalendar().then(res=>{
            this.mainCalendarId = res.data.schoolCalendar.id;
        })
    },

    // 该方法适用于页面第一次点菜的初始化时调用
    initAllData(){
     Calendars.currentTermCalendar().then(res=>{
      this.query.calendarId = res.data.schoolCalendar.id;
      this.query.teacherCode = this.global.currentUser.uid;
      API.getListInfoCount(this.query).then(response => {
        if (response.code === 200) {
          if(this.global.isAdmin || this.global.isAcdemicDean){
            this.query.projectId = this.$store.getters.getProjectId();
          }else{
            let pro = 0;
            response.data.forEach(el => {
              pro = el.projectId;
            })
             let length = response.data.length;
              if(length == 1){
                this.query.projectId = pro; //如果导师为但部门时取他所在部门
              }else if(length > 1){
                this.query.projectId = "1"; //如果为双部门时默认取本科生部门
              }
            
          }
            console.log("this.query.projectId===="+this.query.projectId);
            this.getClassroomApplyInfoList();
        }
      })
    })
    }
  },
   watch: {
    $route(){
      //1 表示此页面为新增页面
      this.getClassroomApplyInfoList();
      this.handelCampusChang(null);
    }
  },
  created() {
    this.initOptions();
    // this.getClassroomApplyInfoList();
    this.initAllData();
    this.handelCampusChang(null);
    this.getListInfoCount(); // 初始化判断管理部门是否显示add by quanwei
  }
};
</script>

<style lang="scss">
  .classroomTable{
    .cell{
      white-space: pre-line;
	  padding: 0 2px;
	  text-align: center;
    }
  }
</style>

